from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render
from django.core.paginator import Paginator
from note.models import Note
from django.contrib.auth.decorators import login_required

# Create your views here.


@login_required
def list_view(request):
    uname=request.session['uname']
    uid=request.session['uid']
    notes=Note.objects.filter(user_id=uid)
    # 分页，每页5个数据
    paginator=Paginator(notes,5)
    # 获取点击的页数的数据，默认为1
    page_num=request.GET.get('page_num',1)
    page=paginator.page(page_num)
    return render(request,'note/list_note.html',locals())


@login_required
def add_view(request):
    if request.method=='GET':
        return render(request,'note/add_note.html')
    elif request.method=='POST':
        title=request.POST.get('title')
        content=request.POST.get('content')
        uid=request.session['uid']
        if not title or not content:
            return HttpResponse('标题或内容不能为空!,<a href="/note/add">返回</a>')
        try:
            Note.objects.create(title=title,content=content,user_id=uid)
        except:
            return HttpResponse('添加笔记失败!,<a href="/note/add">返回</a>')
        return HttpResponseRedirect('/note/')

@login_required

def mod_view(request,id):
    if request.method=='GET':
        note=Note.objects.get(id=id)
        return render(request,'note/mod_note.html',locals())
    elif request.method=='POST':
        title=request.POST.get('title')
        content=request.POST.get('content')
        if not title or not content:
            return HttpResponse('标题或内容不能为空,<a href="/note/add">返回</a>')
        note=Note.objects.get(id=id)
        note.title=title
        note.content=content
        note.save()
        return HttpResponseRedirect('/note/')


@login_required

def del_view(request,id):
    note=Note.objects.get(id=id)
    note.delete()
    return HttpResponseRedirect('/note/')
